﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ArchivingDataModel;
using ArchivingDataWebForms.Helpers;
using BarcodeLib;
using CommunicationManagementBusinessLayer;
using Telerik.Web.UI;
using TelerikHelper;

namespace ArchivingDataWebForms.Pages.Files
{
    public partial class ViewFiles : WebFormBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.iframeBarcode.Attributes["src"] = "";
        }
        protected void AdvancedRadGridResults_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (!e.IsFromDetailTable)
                    {
                        ArchivingDataModel.File[] Files = new ArchivingDataModel.File[] { };
                        if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
                        {
                            long id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                            Files = ent.Files.Where(i => i.Folder.Folder_ID == id).ToArray();
                        }
                        else
                        {
                            this.ShowNotification("من فضلك قم باختيار احد المجلدات", NotificationIconType.Warning);
                        }
                        this.AdvancedRadGridResults.DataSource = Files;
                    }

                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي" + er.Message, NotificationIconType.Error);
                return;
            }
        }
        protected void AdvancedRadGridResults_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "ButtonBarcode".ToLower())
            {

                if (e.CommandArgument != "")
                {
                    string fileID = string.Format("{0:D12}", Convert.ToInt64(e.CommandArgument));
                    int temp = 0;
                    int ratio = 1;

                    //int barcodeWidth = 100;
                    //int barcodeHeight = 30;
                    //int symbolWidth = 30;
                    //int margin = 10;
                    //int descriptionHeght = 10;
                    //barcode alignment
                    AlignmentPositions barcodeAlign = BarcodeLib.AlignmentPositions.CENTER;
                    TYPE barcodeType = TYPE.EAN13;
                    Barcode barcodeObject = new BarcodeLib.Barcode(fileID, barcodeType);
                    barcodeObject.LabelFont = new Font(barcodeObject.LabelFont.FontFamily, 20 * ratio);
                    barcodeObject.Alignment = barcodeAlign;
                    //label alignment and position
                    barcodeObject.IncludeLabel = true;
                    barcodeObject.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
                    barcodeObject.RotateFlipType = RotateFlipType.RotateNoneFlipNone;



                    string guid = Guid.NewGuid().ToString();
                    using (Bitmap bitmapTotal = new Bitmap(673 * ratio, 366 * ratio))
                    {
                        bitmapTotal.SetResolution(300, 300);
                        using (Bitmap bitmapOriginalSymbol = new Bitmap(System.Drawing.Image.FromFile(Server.MapPath("~/images/Logo.png"))))
                        {
                            bitmapOriginalSymbol.SetResolution(300, 300);


                            using (Bitmap bitmapSymbol = new Bitmap(bitmapOriginalSymbol.GetThumbnailImage(160 * ratio, 140 * ratio, null, new IntPtr())))
                            {
                                bitmapSymbol.SetResolution(300, 300);
                                using (Bitmap bitmapBarcode = new Bitmap(barcodeObject.Encode(barcodeType, fileID, Color.Black, Color.White, 555 * ratio, 59 * ratio)))
                                {
                                    bitmapBarcode.SetResolution(300, 300);
                                    using (Graphics g = Graphics.FromImage(bitmapTotal))
                                    {
                                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                        //background
                                        g.FillRectangle(Brushes.White, new Rectangle(0, 0, bitmapTotal.Width, bitmapTotal.Height));
                                        //symbol
                                        //g.DrawImage(bitmapSymbol, new Point(20 * ratio, 15 * ratio));
                                        //barcode
                                        g.DrawImage(bitmapBarcode, new Point(59 * ratio, 310 * ratio));
                                        //strings
                                        StringFormat sf = new StringFormat(StringFormatFlags.DirectionRightToLeft);
                                        //g.DrawString("وزارة الدفاع", new Font("Times New Roman", 6 * ratio, FontStyle.Bold), Brushes.Black, new Point(610 * ratio, 20 * ratio), sf);
                                        // g.DrawString("رئاسة هيئة الاركان العامة", new Font("Times New Roman", 6 * ratio, FontStyle.Bold), Brushes.Black, new Point(650 * ratio, 45 * ratio), sf);
                                        //g.DrawString("الإدارة العامة للأسلحة والمدخرات", new Font("Arial", 11 * ratio, FontStyle.Bold), Brushes.Black, new Point(655 * ratio, 0 * ratio), sf);
                                        g.DrawString("ملف رقم : " + fileID, new Font("Arabic Typesetting", 11 * ratio, FontStyle.Bold), Brushes.Black, new Point(445 * ratio, 85 * ratio), sf);

                                        string s = "";
                                        using (ArchivingDataEntities ent = new ArchivingDataEntities())
                                        {
                                            long id = Convert.ToInt64(fileID);
                                            var file = ent.Files.Include("Folder").FirstOrDefault(i => i.File_ID == id);
                                            s = file.Folder.FolderName_Ar;
                                            if (file.Folder.ParentFolder_ID.HasValue)
                                            {
                                                s += "/" + ent.Folders.FirstOrDefault(i => i.Folder_ID == file.Folder.ParentFolder_ID).FolderName_Ar;
                                            }
                                            s += "/" + file.FileTitle_Ar;
                                        }
                                        g.DrawString(s, new Font("Arabic Typesetting", 15 * ratio, FontStyle.Bold), Brushes.Black, new Point(660 * ratio, 185 * ratio), sf);



                                        //g.DrawString(this.reverseString(this.mWared.Wared_Number) + "   -  " + this.calCurrentDate.CurrentYear, new Font("Times New Roman", descriptionHeght), Brushes.Black, new Point(margin * 2 + barcodeWidth + symbolWidth, margin + barcodeHeight), sf);
                                        //Pen pen = new Pen(Color.Gray, 2);
                                        //pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                                        //g.DrawRectangle(pen, 0, 0, barcodeWidth + symbolWidth + 2 * margin, barcodeHeight + descriptionHeght + 2 * margin);
                                        //g.DrawRectangle(new Pen(Color.Red,10),new Rectangle (0,0,673,366));
                                    }
                                }
                            }
                            this.PrintAll(bitmapTotal, 1);
                            //using (Bitmap Bitmapfinal = this.repeatImage(bitmapTotal, temp, 1))
                            //{
                            //}
                        }
                        //bitmapTotal.Save(@"C:\Users\ahmed\Desktop\123.jpg");
                        //bitmapTotal.Save(Server.MapPath("../Arabic/" + guid + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
                        //ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "window.open('../Arabic/" + guid + ".jpg','_blank');", true);
                    }
                }
                else
                {
                    this.ShowNotification("من فضلك قم بحفظ الملف اولا", NotificationIconType.Warning);
                }
            }
            else if (e.CommandName.ToLower() == "ButtonScanner".ToLower())
            {
                if (e.CommandArgument != "")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "scan", "startSilverLightScan(\"" + this.RadButtonSilverLightEnd.ClientID + "\",\"" + e.CommandArgument + "\",\"55555\")", true);
                }
                else
                {
                    this.ShowNotification("من فضلك قم بحفظ الملف اولا", NotificationIconType.Warning);
                }
            }
            else if (e.CommandName.ToLower() == "ButtonUpload".ToLower())
            {
                if (e.CommandArgument != "")
                {
                    using (ArchivingDataEntities ent = new ArchivingDataEntities())
                    {
                        RadAsyncUpload radAU = (RadAsyncUpload)e.Item.FindControl("RadAsyncUploadatt");
                        if (radAU.UploadedFiles.Count > 0)
                        {
                            long id = Convert.ToInt64(e.CommandArgument);
                            string code = "";
                            string titleAr = "";
                            string noteAr = "";
                            string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + titleAr + noteAr);
                            int order = ent.Files.FirstOrDefault(i => i.File_ID == id).Attachments.Count() + 1;
                            ArchivingDataModel.Attachment item = new ArchivingDataModel.Attachment
                            {
                                Attachment_Order = order,
                                Attachment_Code = code,
                                AttachmentTitle_Ar = titleAr,
                                AttachmentNote_Ar = noteAr,
                                Attachment_UniqueText = uniquetext
                            };
                            ent.Files.FirstOrDefault(i => i.File_ID == id).Attachments.Add(item);
                            ent.SaveChanges();
                            string imagePath = CustomAppSettings.DefaultFileImagePath;
                            string datePath = DateTime.Now.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
                            imagePath = CustomAppSettings.FilesPathes + "/" + datePath + "/" + item.Attachment_ID + radAU.UploadedFiles[0].GetExtension();
                            Directory.CreateDirectory(Path.GetDirectoryName(CustomAppSettings.getActualPath(imagePath)));
                            radAU.UploadedFiles[0].SaveAs(CustomAppSettings.getActualPath(imagePath));

                            item.Attachment_Path = imagePath;
                            item.MimeType = radAU.UploadedFiles[0].ContentType;
                            if (item.MimeType == null)
                            {
                                item.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromExtension(radAU.UploadedFiles[0].GetExtension());
                                if (item.MimeType == null)
                                {
                                    item.MimeType = WebHelper.Helpers.MimeTypeHelper.getMimeFromFile(CustomAppSettings.getActualPath(imagePath));
                                }
                            }
                            ent.SaveChanges();
                            this.ShowNotification("تم الرفع بنجاح", NotificationIconType.Ok);
                        }
                    }

                }
                else
                {
                    this.ShowNotification("من فضلك قم بحفظ الملف اولا", NotificationIconType.Warning);
                }

            }

        }

        private void PrintAll(Bitmap bitmap, int count)
        {
            string CasheName = "CasheName";
            List<System.Drawing.Image> lstImages = new List<System.Drawing.Image>();

            Size sz = new Size(bitmap.Width, bitmap.Height);
            for (int i = 0; i < count; i++)
            {
                lstImages.Add(bitmap);

            }



            byte[] btNew = PDFCreateFromImages.createBarcodeFile(lstImages, new Rectangle(new Point(0, 0), sz), true);
            string cacheKey = Guid.NewGuid().ToString();
            this.Cache.Add(cacheKey, btNew, null, DateTime.Now.Add(new TimeSpan(0, 20, 0)), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
            this.iframeBarcode.Attributes["src"] = "DisplayPdf.aspx" + "?" + CasheName + "=" + cacheKey;

            //ScriptManager.RegisterStartupScript(this, this.GetType(), "print", "window.open('" + UrlMapper.RelativeAspxPages.DisplayPdf + "?" + CasheName + "=" + cacheKey + "','_blank');", true);
        }
        protected void RadButtonSilverLightEnd_Click(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(this.Request.Url.ToString());
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي", NotificationIconType.Error);
            }
        }


        //if (e.CommandName.ToLower() == AdvancedRadGrid.InitInsertCommandName.ToLower())
        //{
        //    if( !string.IsNullOrEmpty( this.Request.QueryString[QueryStringParams.Folder_ID]))
        //    {
        //        this.Response.Redirect(WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Files/AddFile.aspx?" + QueryStringParams.Folder_ID + "=" + this.Request.QueryString[QueryStringParams.Folder_ID]));
        //    }
        //}
        //else if (e.CommandName.ToLower() == AdvancedRadGrid.EditCommandName.ToLower())
        //{
        //    if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
        //    {
        //        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["File_ID"]);
        //        this.Response.Redirect(WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Files/AddFile.aspx?" + QueryStringParams.File_ID + "=" + id));
        //    }
        //}
        protected void AdvancedRadGridResults_InsertCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridEditableItem editedItem = e.Item as GridEditableItem;
                    long folderID = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        string code = newValues["File_code"].ToString();
                        string title_Ar = newValues["FileTitle_Ar"].ToString();
                        string subject = newValues["FileSubject_Ar"].ToString();
                        string noteAr = newValues["FileNote_Ar"].ToString();
                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + title_Ar + subject + noteAr);
                        ent.AddToFiles(new ArchivingDataModel.File()
                        {
                            File_Code = code,
                            FileTitle_Ar = title_Ar,
                            FileSubject_Ar = subject,
                            FileNote_Ar = noteAr,
                            File_UniqueText=uniquetext,
                            Folder = ent.Folders.FirstOrDefault(i => i.Folder_ID == folderID)
                        });
                        ent.SaveChanges();
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "RefreshParentTree", "window.parent.RefreshFolderTree('" + this.Request.QueryString[QueryStringParams.Folder_ID] + "')", true);
                    }
                    else if (e.Item.OwnerTableView.Name == "master")
                    {
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridEditableItem editedItem = e.Item as GridEditableItem;
                    long folderID = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["File_ID"]);
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        string code = newValues["File_code"].ToString();
                        string title_Ar = newValues["FileTitle_Ar"].ToString();
                        string subject = newValues["FileSubject_Ar"].ToString();
                        string noteAr = newValues["FileNote_Ar"].ToString();
                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + title_Ar + subject + noteAr);
                        var file = ent.Files.FirstOrDefault(i => i.File_ID == id); 
                            file.File_Code = code;
                            file.FileTitle_Ar = title_Ar;
                            file.FileSubject_Ar = subject;
                            file.FileNote_Ar = noteAr;
                            file.File_UniqueText = uniquetext;
                        ent.SaveChanges();
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "RefreshParentTree", "window.parent.RefreshFolderTree('" + this.Request.QueryString[QueryStringParams.Folder_ID] + "')", true);
                    }
                    else if (e.Item.OwnerTableView.Name == "master")
                    {
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["File_ID"]);
                        ent.DeleteObject(ent.Files.FirstOrDefault(i => i.File_ID == id));
                        ent.SaveChanges();
                        this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "master")
                    {
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحذف " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_ItemDataBound(object sender, GridItemEventArgs e)
        {
            //try
            //{
            //    using (ArchivingDataEntities ent = new ArchivingDataEntities())
            //    {
            //        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            //        {
            //            GridEditableItem editedItem = e.Item as GridEditableItem;
            //            if (e.Item.OwnerTableView.Name == "CustomFields")
            //            {
            //                RadDropDownList rDDLCFieldType = (RadDropDownList)editedItem.FindControl("RadDropDownListCFieldType");
            //                if (rDDLCFieldType != null)
            //                {
            //                    var items = ent.CusFieldsTypes.ToArray();
            //                    rDDLCFieldType.DataSource = items;
            //                    rDDLCFieldType.DataTextField = "CFieldTypeName_Ar";
            //                    rDDLCFieldType.DataValueField = "CFieldType_ID";
            //                    if (items.Count() > 0)
            //                    {
            //                        rDDLCFieldType.SelectedIndex = 0;
            //                    }
            //                    rDDLCFieldType.DataBind();

            //                    RadDropDownList rDDLCusField = (RadDropDownList)editedItem.FindControl("RadDropDownListCusField");
            //                    if (rDDLCusField != null)
            //                    {
            //                        long id = Convert.ToInt64(rDDLCFieldType.SelectedValue);
            //                        long FileTypeID = Convert.ToInt64(editedItem.OwnerTableView.ParentItem.GetDataKeyValue("FileType_ID"));
            //                        var currentIDs = ent.FilesTypes_CusFields.Where(i => i.FilesType.FileType_ID == id).Select(i => i.CusField.CusField_ID).ToList();
            //                        var CusFieldsitems = ent.CusFields.Where(i => i.CusFieldsType.CFieldType_ID == id).ToArray().Where(i => !currentIDs.Contains(i.CusField_ID));
            //                        rDDLCusField.DataSource = CusFieldsitems;
            //                        rDDLCusField.DataTextField = "CusFieldName";
            //                        rDDLCusField.DataValueField = "CusField_ID";
            //                        if (CusFieldsitems.Count() > 0)
            //                        {
            //                            rDDLCusField.SelectedIndex = 0;
            //                        }
            //                        rDDLCusField.DataBind();
            //                    }
            //                }
            //            }
            //            else if (e.Item.OwnerTableView.Name == "master")
            //            {
            //            }
            //        }
            //    }
            //}
            //catch (Exception er)
            //{
            //    this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
            //    e.Canceled = true;
            //    return;
            //}
        }

        protected void AdvancedRadGridResults_ItemCreated(object sender, GridItemEventArgs e)
        {

            if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
            {
                GridEditableItem item = (GridEditableItem)e.Item;
                
                RadDatePicker pkr = (RadDatePicker)item["FromDate"].Controls[0];
                CultureInfo cul = CultureInfo.CreateSpecificCulture("ar-sa");
                cul.DateTimeFormat.Calendar=new  GregorianCalendar();
                pkr.Culture = cul;

                RadDatePicker pkr2 = (RadDatePicker)item["ToDate"].Controls[0];
                pkr2.Culture = cul;

            }



            if (e.Item is GridFilteringItem)
            {
                GridFilteringItem filteringItem = e.Item as GridFilteringItem;
                //set dimensions for the filter textbox  
                TextBox box = filteringItem["File_code"].Controls[0] as TextBox;
                TextBox box1 = filteringItem["FileTitle_Ar"].Controls[0] as TextBox;
                TextBox box2 = filteringItem["FileSubject_Ar"].Controls[0] as TextBox;
                TextBox box3 = filteringItem["FileNote_Ar"].Controls[0] as TextBox;
                box.Width = Unit.Pixel(20);
                box1.Width = Unit.Pixel(80);
                box2.Width = Unit.Pixel(80);
                box3.Width = Unit.Pixel(80);
            }
        }
    }
}